#define _GNU_SOURCE

#include <stdio.h>
#include <string.h>
#include <regex.h>

// 函数原型
int check_phone_num(char * num);

int main()
{
    int i;
    char *s[] = {"029-849-1249", "1-885-1202", "876-9182",
                 "1923-989-2912", "0591-089-2126", "021-29-8932",
                 "9280-9981", "910-92817", "01-9A9-8712",
                 "298491249", "0086-010-102-9182",
                 "A09-021-928-1921", "123-1211", "29-1+983"};

    for(i = 0; i < sizeof(s) / sizeof(s[0]); i++)
    {
        if(check_phone_num(s[i]))
        {
            printf("%s is valid phonenum.\n", s[i]);
        }
        else
        {
            printf("%s is not valid phonenum.\n", s[i]);
        }
    }

    return 0;
}

int check_phone_num(char * num)
{
    // 声明struct re_pattern_buffer对象
    struct re_pattern_buffer pat_buf;
    const char *err_code;
    int match_ret;

    memset(&pat_buf, 0, sizeof(struct re_pattern_buffer));
    re_set_syntax(RE_SYNTAX_EGREP);

    // 正则表达式
    const char* pat = "^(([0-9]{0,4})-)?[1-9][0-9]{2}-[0-9]{4}$";

    // 编译正则表达式
    err_code  = re_compile_pattern(pat, strlen(pat), &pat_buf);
    if(err_code != NULL)
    {
        printf("erro: %s\n", err_code);
        regfree(&pat_buf);
        return 0;
    }

    // 匹配检查
    match_ret = re_match(&pat_buf, num, strlen(num), 0, NULL);

    // 释放空间
    regfree(&pat_buf);

    return match_ret >= 0 ? 1 : 0;
}
